package com.david.jetpack.room

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.room.Room
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.david.jetpack.R
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import kotlin.random.Random

//参考链接：https://developer.android.google.cn/training/data-storage/room?hl=zh-cn
//https://juejin.cn/post/7090222693303189534
//https://developer.android.google.cn/training/data-storage/room/accessing-data?hl=zh-cn
//https://blog.csdn.net/ShiXinXin_Harbour/article/details/115077960
//https://blog.csdn.net/github_34402358/article/details/103201663
class RoomTestActivity: AppCompatActivity() {

    private var db: AppDatabase? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_room_test)


        db = Room.databaseBuilder(
            applicationContext,
            AppDatabase::class.java, "database-name"
        ).addMigrations(object : Migration(2, 3) {
            override fun migrate(database: SupportSQLiteDatabase) {
//                database.execSQL("create table if not exists 'school'('id' INTEGER, 'name' CHAR)")
                database.execSQL("create table if not exists 'address'('id' TEXT, 'latitude' REAL,'longitude' REAL, PRIMARY KEY(`id`))")
            }

        })
            .build()
    }

    fun add(v: View?) {
        CoroutineScope(Dispatchers.IO).launch {
            val userDao = db?.userDao()
            userDao?.insertAll(User(111, firstName = "san", lastName = "zhang"))
        }
    }

    fun get(v: View?) {
        CoroutineScope(Dispatchers.IO).launch {

            val userDao = db?.userDao()
//            val users: List<User>? = userDao?.getAll()
            userDao?.findByFirstName("san")?.collectLatest {
                Log.e("room", "size is ${it?.size}")
            }
        }
    }

    fun insertAddress(view: View?) {
        lifecycleScope.launch(Dispatchers.IO) {
            val addressDao = db?.addressDao()
//            addressDao?.insertAddr(AddressInfo("11111", 29.910000f,120.759999f, "test address"))
            Log.e("room", "insert start...")
            var lng = 0f
            var lat = 0f
            val list = ArrayList<AddressInfo>()
            for (i in 0..100000) {
                lat = getRandomLat()
                lng = getRandomLng()
                list.add(AddressInfo("$lat$lng", lat,lng, "test address$lat $lng"))
            }
            addressDao?.insertAllAddr(list)
            Log.e("room", "insert finish...")
        }
    }

    fun getRandomLat(): Float {
//        val lngStart = 119890000 //869999
        val latStart = 29910000f  //389999
//        val random = Random(869999)
//        val lngValue = random.nextInt() / 1000000.0
        val latValue = (latStart+Random.nextInt(389999)) / 1000000.0f

        // fmt.Printf("lngValue is %f\n", lngValue)
        // fmt.Printf("latValue is %f", latValue)
        return latValue
    }
    fun getRandomLng (): Float {
        val lngStart = 119890000f //869999
//        val latStart = 29910000  //389999
//        val random = Random(389999)
//        val lngValue = random.nextInt() / 1000000.0
        val lngValue = (lngStart+Random.nextInt(869999)) / 1000000.0f

        // fmt.Printf("lngValue is %f\n", lngValue)
        // fmt.Printf("latValue is %f", latValue)
        return lngValue
    }

    /**
     * 从20万条数据中
     * 查询4万条约200ms
     * 查询22000用时110ms
     * 查询5100用时50ms
     */
    fun queryAddress(view: View?) {
        lifecycleScope.launch(Dispatchers.IO) {
            Log.e("room", "querystart...")

            val addressDao = db?.addressDao()
            val addresses = addressDao?.queryRangeAddress(120.72f,120.759999f, 29.999999f, 30.21f)

            addresses?.collectLatest {
                if (addresses != null) {
                    //                for (item in addresses) {
                    //                    Log.e("room", item.addressName)
                    //                }

                    Log.e("room", "size is ${it.size}")

                }
            }
        }
    }

    /**
     * 查询10万条约350ms
     */
    fun getAddress(view: View?) {
        lifecycleScope.launch(Dispatchers.IO) {
            val addressDao = db?.addressDao()
            Log.e("room", "querystart...")

            val addresses = addressDao?.getAll()

//            if (addresses != null) {
//                for (item in addresses) {
//                    Log.e("room", item.addressName)
//                }
//            }
            addresses?.collectLatest {
                Log.e("room", "size is ${it.size}")
            }
        }
    }

    fun deleteAddress(view: View?) {
        lifecycleScope.launch(Dispatchers.IO) {
            val addressDao = db?.addressDao()
            val addresses = addressDao?.deleteAll()
        }
    }
}